package patternmining.model.construction;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @version 1.0, 04.07.2008
 * @author Holger Wiehen
 */
class TypeNameQualifier {
    
    private PackageIndex packageIndex;
    
    public Map<String , Set<String> > shortNameToQualifiedNameMapping;
    public Set<String> qualifiedNames;
    
    public TypeNameQualifier(PackageIndex userDefinedPackages, String ownPackage){
        this.packageIndex = userDefinedPackages;
        shortNameToQualifiedNameMapping = new HashMap<String, Set<String> >();
        qualifiedNames = new HashSet<String>();
        addPrimitiveTypes();
        addPackageImport(ownPackage);
    } 
    
    private void addPrimitiveTypes(){
        qualifiedNames.add("java.lang.Boolean");
        qualifiedNames.add("java.lang.Character");
        qualifiedNames.add("java.lang.Byte");
        qualifiedNames.add("java.lang.Short");
        qualifiedNames.add("java.lang.Integer");
        qualifiedNames.add("java.lang.Long");
        qualifiedNames.add("java.lang.Float");
        qualifiedNames.add("java.lang.Double");
    }
    
    public void addPackageImport(String importValue){
        String[] packageMembers = packageIndex.getMembersOfPackage(importValue);
        for( String member : packageMembers ){
            String shortName = member.substring( member.lastIndexOf(".") + 1 );
            addPair(shortName, member);
        }
    }
    
    public void addSingleTypeImport(String importValue){
        String shortName = importValue.substring( importValue.lastIndexOf(".") + 1 );
        addPair(shortName, importValue);
    }
   
    private void addPair(String shortName, String qualifiedName){
        Set<String> associatedQualifiedNames =  shortNameToQualifiedNameMapping.get(shortName);
            if( associatedQualifiedNames != null ){
                associatedQualifiedNames.add(qualifiedName);
            }
            if( associatedQualifiedNames == null ){
                associatedQualifiedNames = new HashSet<String>();
                associatedQualifiedNames.add(qualifiedName);
                shortNameToQualifiedNameMapping.put(shortName, associatedQualifiedNames);
            } 
            qualifiedNames.add(qualifiedName);
    }
    
   public String[] getQualifiedTypeName(String typeName){
        String[] name = null;
        if ( qualifiedNames.contains(typeName) ){
            name = new String[1];
            name[0] = typeName;
        }
        else{
            Set<String> associatedQualifiedNames = shortNameToQualifiedNameMapping.get( typeName );
            if( associatedQualifiedNames == null ) return null;
            if( associatedQualifiedNames != null ) name = associatedQualifiedNames.toArray( new String[ associatedQualifiedNames.size() ]);
        }
        
        return name;
   }
   
  
   
}
